package com.eagle.scali.usercenter.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.eagle.scali.commoncenter.auth.CheckLogin;
import com.eagle.scali.commoncenter.util.JwtOperator;
import com.eagle.scali.usercenter.dao.user.UserMapper;
import com.eagle.scali.usercenter.domain.dto.content.ShareDTO;
import com.eagle.scali.usercenter.domain.dto.messaging.UserAddBonusMsgDTO;
import com.eagle.scali.usercenter.domain.dto.user.JwtTokenRespDTO;
import com.eagle.scali.usercenter.domain.dto.user.LoginRespDTO;
import com.eagle.scali.usercenter.domain.dto.user.UserLoginDTO;
import com.eagle.scali.usercenter.domain.dto.user.UserRespDTO;
import com.eagle.scali.usercenter.domain.entity.bonus.BonusEventLog;
import com.eagle.scali.usercenter.domain.entity.user.User;
import com.eagle.scali.usercenter.service.user.UserService;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/users")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@ComponentScan(basePackages = { "com.eagle.scali.commoncenter"})
@Slf4j
public class UserController {

	private final UserService userService;

	private final JwtOperator jwtOperator;

	private final WxMaService wxMaService;

	/**
	 *	X-Token:eyJhbGciOiJIUzI1NiJ9.eyJpZCI6NCwid3hOaWNrbmFtZSI6IumjniIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTU4NjI3MDEzMiwiZXhwIjoxNTg3NDc5NzMyfQ.Y-K9mxCgyvEQnqP-3pArAGfvcYnA_Ylkjj7P-Y7gr4g
	 *	http://localhost:8060/users/4
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	@CheckLogin
	public User findById(@PathVariable Integer id) {
		log.info("我被请求了...");
		return this.userService.findById(id);
	}


	@GetMapping("/me")
	@CheckLogin
	public User fineMe(@RequestHeader(value = "X-Token", required = false) String token) {
		Claims claims = this.jwtOperator.getClaimsFromToken(token);
		Integer userId = (Integer) claims.get("id");
		return this.userService.findById(userId);
	}

	@GetMapping("/bonus-logs")
	@CheckLogin
	public List<BonusEventLog> bonusLogs(@RequestHeader(value = "X-Token", required = false) String token) {
		Claims claims = this.jwtOperator.getClaimsFromToken(token);
		Integer userId = (Integer) claims.get("id");
		return this.userService.findBonusLogById(userId);
	}

	@GetMapping("/contributions")
	@CheckLogin
	public List<ShareDTO> contributions(@RequestHeader(value = "X-Token", required = false) String token) {
		Claims claims = this.jwtOperator.getClaimsFromToken(token);
		Integer userId = (Integer) claims.get("id");
		return this.userService.findContributionsById(userId);
	}

	/**
	 * http://localhost:8060/users/gen-token
	 * 模拟生成token(假的登录)
	 */
	@GetMapping("/gen-token")
	public String genToken() {
		Map<String, Object> userInfo = new HashMap<>(3);
		userInfo.put("id", 10000);
		userInfo.put("wxNickname", "审批用户");
		userInfo.put("role", "approver");
		return this.jwtOperator.generateToken(userInfo);
	}

	@PostMapping("/login")
	public LoginRespDTO login(@RequestBody UserLoginDTO loginDTO) throws WxErrorException {
		// 微信小程序服务端校验是否已经登录的结果
		WxMaJscode2SessionResult result = this.wxMaService.getUserService()
				.getSessionInfo(loginDTO.getCode());

		// 微信的openId，用户在微信这边的唯一标示
		String openid = result.getOpenid();

		// 看用户是否注册，如果没有注册就（插入）
		// 如果已经注册
		User user = this.userService.login(loginDTO, openid);

		// 颁发token
		Map<String, Object> userInfo = new HashMap<>(3);
		userInfo.put("id", user.getId());
		userInfo.put("wxNickname", user.getWxNickname());
		userInfo.put("role", user.getRoles());

		String token = jwtOperator.generateToken(userInfo);

		log.info(
				"用户{}登录成功，生成的token = {}, 有效期到:{}",
				loginDTO.getWxNickname(),
				token,
				jwtOperator.getExpirationTime()
		);

		// 构建响应
		return LoginRespDTO.builder()
				.user(
						UserRespDTO.builder()
								.id(user.getId())
								.avatarUrl(user.getAvatarUrl())
								.bonus(user.getBonus())
								.wxNickname(user.getWxNickname())
								.build()
				)
				.token(
						JwtTokenRespDTO.builder()
								.expirationTime(jwtOperator.getExpirationTime().getTime())
								.token(token)
								.build()
				)
				.build();

	}
}
